package com.wufun.baselibrary.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

/**
 * Created by yangg on 2017/11/14.
 *
 *
 */

public class Xzip {
    /**
     * 纯 解压缩含有文件夹的压缩文件
     *
     * @param zipFile
     * @param folderPath
     * @throws ZipException
     * @throws IOException
     */
    public static boolean upZipFile(File zipFile, String folderPath) throws
            IOException {
        File desDir = new File(folderPath);
        if (!desDir.exists()) {
            // 创建目标目录
            desDir.mkdirs();
        }
        ZipFile zf = new ZipFile(zipFile);
        for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = ((ZipEntry) entries.nextElement());
            if (entry.isDirectory()) {
                String tmpStr = folderPath + File.separator + entry.getName();
                tmpStr = new String(tmpStr.getBytes("8859_1"), "UTF-8");
                File folder = new File(tmpStr);
                folder.mkdirs();
            } else {
                InputStream is = zf.getInputStream(entry);
                String str = folderPath + File.separator + entry.getName();
                // 转换编码，避免中文时乱码
                str = new String(str.getBytes("8859_1"), "UTF-8");

                File desFile = new File(str);
                //如果文件存在删除他。防止文件已经存在不能解压的问题
                if (desFile.exists()) {
                    File f = new File(desFile.getParent() + "/" + System.currentTimeMillis());
                    desFile.renameTo(f);
                    f.delete();
                }
                if (!desFile.exists()) {
                    // 创建目标文件
                    File fileParentDir = desFile.getParentFile();
                    if (!fileParentDir.exists()) {
                        fileParentDir.mkdirs();
                    }
                    desFile.createNewFile();

                }
                OutputStream os = new FileOutputStream(desFile);
                byte[] buffer = new byte[1024*4];
                int realLength;

                while ((realLength = is.read(buffer)) > 0) {
                    os.write(buffer, 0, realLength);
                    os.flush();
                }
                is.close();
                os.close();

            }


        }
        zf.close();
        return true;
    }

}
